import myconfig  from "@/config/index";
import store from '@/config/store.js';
import md5js from "@/config/md5.js";
import { http } from '@/utils/luch-request/index.js'
export const tools = {
	filters: {

	},
	computed: {

	},
	methods: {
		//富文本的回调
		navigate(e) {
			if (e.href && e.href.indexOf('http') == -1) { //不完整的链接						
				//详情				
				let res = e.href.match(new RegExp("(a)|(\\d+)", 'g'));
				if (res.length == 2) {
					this.$u.route('/pages/article/detail', {
						id: res[1]
					});
					return;
				}
				// #ifdef MP
				this.$util.uniCopy({
					content: this.vuex_config.upload.cdnurl + e.href,
					success: () => {
						this.$u.toast('链接已复制,请在浏览器中打开')
					}
				})
				// #endif
				// #ifndef MP				
				window.open(this.vuex_config.upload.cdnurl + e.href);
				// #endif
			}
		},
		//预览图片
		lookImage(index) {
			uni.previewImage({
				current: index,
				urls: this.imagesList,
				longPressActions: {
					itemList: ['发送给朋友', '保存图片', '收藏'],
					success: function(data) {
						console.log(data)
					},
					fail: function(err) {
						console.log(err.errMsg);
					}
				}
			});
		},
		//复制url
		copyUrl() {
			this.$util.uniCopy({
				content: window.location.href,
				success: () => {
					this.$u.toast('复制成功，请去粘贴发送给好友吧');
				},
				error: () => {
					console.log('复制失败！')
				}
			})
		},
		//cdnurl
		cdnurl(url) {
			if (!/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/.test(url)) {
				return this.vuex_config.upload.cdnurl + url;
			};
			return url;
		},
		//页面跳转
		goPage(path, auth) {
			if (path == 'out') {
				this.$u.vuex('vuex_token', '');
				this.$u.vuex('vuex_user', {});
				this.$u.route({
								url: '/pages/mine/index',
								type:'switchTab'
							})

				return;
			}
			if (auth && !this.vuex_token) {
				this.$u.route('/pages/login/selLogin');
				return;
			}
			let type = 'navigateTo';
			
			// #ifdef MP-WEIXIN
			//优化当pages超过5个时的处理
			let pages = getCurrentPages();
			type = pages.length >= 4 ? 'redirectTo' : type;
			// #endif
			
			uni.$u.route({
				url: path,
				type: type,
				complete(e) {
					console.log(e, path)
				}
			})
		},
		checkUserInfo(type,userInfo){
			type = type?type:'get';
			userInfo = userInfo?userInfo:{};
			switch(type)
			{
				case 'set':
					uni.setStorageSync('cache_userInfo',userInfo);
					break;
				case 'get':
					if(this.checkLogin() == false)
					{
						return {};
					}
					var userInfo = uni.getStorageSync('cache_userInfo');
					if(!userInfo || userInfo == '')
					{
						return {};
					}
					return userInfo;
					break;
				case 'del':
					uni.removeStorageSync('cache_userInfo');
					break
			}
		},
		checkLogin(showForceLogin)
		{
			var token = this.jwtToken();
			if(!token)
			{
				this.checkUserInfo('del'); //清除本地缓存的用户信息
				store.commit('loginStatus', false);
				if(showForceLogin == true)
				{
					store.commit('showForceLogin', true);
				}
				return false;
			}else{
				store.commit('loginStatus', true);
				return true;
			}
		},
		jwtToken:function(type,tokenObj){
			type = type?type:'get';
			tokenObj = tokenObj?tokenObj:{};
			switch(type)
			{
				case 'set':
					uni.setStorageSync('jwt_token',tokenObj.jwt_token);
					uni.setStorageSync('jwt_token_exp_time',tokenObj.exp_time);
					this.checkLogin();//更改登录状态
					break;
				case 'get':
					var jwt_token = uni.getStorageSync('jwt_token');
					if(!jwt_token || jwt_token == '')
					{
						return '';
					}
					var jwt_token_exp_time = uni.getStorageSync('jwt_token_exp_time');
					jwt_token_exp_time = jwt_token_exp_time?parseInt(jwt_token_exp_time):0;
					if(jwt_token_exp_time < this.getTime())
					{
						this.jwtToken('del'); 
						return '';
					}
					return jwt_token;
					break;
				case 'del':
					uni.removeStorageSync('jwt_token');
					uni.removeStorageSync('jwt_token_exp_time');
					this.checkLogin();//更改登录状态
					break
			}
		},
		//获取当前时间
		getTime:function(){
			var time = Date.now();
			return parseInt(time/1000);
		},
		//时间转时间戳
		timeToNumber(time){
			var that = this;
			if(!time || time == '')
			{
				return 0;
			}
			var intTime = 0;
			try{
				intTime = new Date(time.replace(/-/g, '/')).getTime() / 1000;
			}catch(e){
				that.msg('时间转换错误')
			}
			return intTime;
		},
		getDateRange:function(dateNow,intervalDays,resLength,bolPastTime){
			dateNow = dateNow?dateNow:new Date();
			resLength = resLength?parseFloat(resLength):3;
			let oneDayTime = 24 * 60 * 60 * 1000;
			let list = [];
			let lastDay;
		
			if(bolPastTime == true){
				lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
				list.push(this.formateDate(lastDay,resLength));
				list.push(this.formateDate(dateNow,resLength));
			}else{
				lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
				list.push(this.formateDate(dateNow,resLength));
				list.push(this.formateDate(lastDay,resLength));
			}
			return list;
		},
		formateDate:function(time,length){
			let year = time.getFullYear();
			year = year > 9 ? year : '0' + year.toString();
			let month = time.getMonth() + 1;
			month = month > 9 ? month : '0' + month.toString();
			let day = time.getDate();
			day = day > 9 ? day : '0' + day.toString();
			let hour = time.getHours();
			hour = hour > 9 ? hour : '0' + hour.toString()
			let minute = time.getMinutes();
			minute = minute > 9 ? minute : '0' + minute.toString()
			let second = time.getSeconds();
			second = second > 9 ? second : '0' + second.toString()
			switch(length){
				case 1:
					return year;
				case 2:
					return year + '/' + month;
				case 3:
					return year + '-' + month + '-' + day + '';
				case 4:
					return year + '-' + month + '-' + day + ' '+hour;
				case 5:
					return year + '-' + month + '-' + day + ' '+hour+':'+minute;
				case 6:
					return year + '-' + month + '-' + day + ' '+hour+':'+minute+':'+second;
				default:
					return '';
			}
			
		},
		splitStrRN:function(str,checkRepeat,checkTrim=1){
			//checkTrim 是否排除只是空白的内容
			if(!str)
			{
				return {
					status:true,
					list:[]
				};
			}
			//checkRepeat 是否检测重复
			str = str.replace(/\n/g,',');
			str = str.replace('，',',');
			var strArr = str.split(",");
			if(strArr.length < 1)
			{
				return {
					status:true,
					list:[]
				};
			}
			if(checkTrim == 1)
			{
				for(var i=0;i<strArr.length;i++)
				{
					strArr[i] =  strArr[i] && strArr[i].replace(/\n/g,'') && strArr[i].trim(); 
				}
				strArr = strArr.filter(function (s) {
				    return s && s.trim(); 
				})
			}
			var hasRepeat = false;
			if(checkRepeat)
			{
				var newStrArr = [];
				for(var i=0;i<strArr.length;i++) {
					if(newStrArr.indexOf(strArr[i]) > -1)
					{
						this.msg(`填写的内容中"${strArr[i]}"重复`);
						hasRepeat = true;
						break;
					}else{
						newStrArr.push(strArr[i]);
					}
				}
			}
			if(hasRepeat)
			{
				return {
					status:false,
					list:[]
				};
			}
			return {
				status:true,
				list:strArr
			};
		},
		isPhoneNumber:function(mobile){
			if(!mobile){
				return false;
			}
			var reg =/^0?1[1|2|3|4|5|6|7|8|9][0-9]\d{8}$/;
			return reg.test(mobile);
		},
		checkEmail(email){
			if(!email)
			{
				return false;
			}
			var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
			//调用正则验证test()函数
			var isok= reg.test(email);
			if(!isok) {
				return false;
			}
			return true;
		},
		checkCard:function(card)
		{
			if(!card)
			{
				return false;
			}
		    card=card.toLowerCase();
		    var vcity={ 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
		    var arrint = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
		    var arrch = new Array('1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2');
		    var reg = /(^\d{15}$)|(^\d{17}(\d|x)$)/;
		    if(!reg.test(card))return false;
		    if(vcity[card.substr(0,2)] == undefined)return false;
		    var len=card.length;
		    if(len==15)
		        reg=/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
		    else
		        reg=/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|x)$/;
		    var d,a = card.match(new RegExp(reg));
		    if(!a)return false;
		    if (len==15){
		        d = new Date("19"+a[2]+"/"+a[3]+"/"+a[4]);
		    }else{
		        d = new Date(a[2]+"/"+a[3]+"/"+a[4]);
		    }
		    if (!(d.getFullYear()==a[2]&&(d.getMonth()+1)==a[3]&&d.getDate()==a[4]))return false;
		    if(len=18)
		    {
		        len=0;
		        for(var i=0;i<17;i++)len += card.substr(i, 1) * arrint[i];
		        return arrch[len % 11] == card.substr(17, 1);
		    }
		    return true;
		},
		checkChinese:function(item){
		    // console.log(item)     
			var re = /[^\u4e00-\u9fa5]/;
			if (re.test(item)) {
		        return false;
		    } 
			return true;
		},
		checkEnglish:function(item){
		    // console.log(item)     
			var re = /[^\a-\z\A-\Z]/g;
			if (re.test(item)) {
		        return false;
		    } 
			return true;
		},
		checkEnNumber:function(item){
		    // console.log(item)     
			var re = /[^\a-z\A-Z\0-9]/g;
			if (re.test(item)) {
		        return false;
		    } 
			return true;
		},
		makePhone:function(phone){
			if(!this.isPhoneNumber(phone)){
				this.msg('不是正确的手机号');
				return false;
			}
			uni.makePhoneCall({
				phoneNumber: phone //仅为示例
			});
		},
		msg:function(title, duration=1000, mask=false, icon='none'){
			title = title?title.toString():'';
			//统一提示方便全局修改
			if(Boolean(title) === false){
				return;
			}
			uni.showToast({
				title,
				duration,
				mask,
				icon
			});
		},
		loadingMsg:function(title,mask=true){
			title = title?title.toString():'';
			//统一提示方便全局修改
			//if(Boolean(title) === false){return;}
			uni.showLoading({title,mask,});
		},
		showModal2:function(title,content,callback,params){
			title = title?title.toString():'提示';
			var showCancel = (params && params.hideCancel)?false:true;
			var confirmText = (params && params.confirmText)?params.confirmText:'确定';
			uni.showModal({
			    title: title,
			    content: content,
				showCancel:showCancel,
				confirmText:confirmText,
			    success: function (res) {
			        if (res.confirm) {
			            var returnRes = 'yes';
			        } else if (res.cancel) {
						var returnRes = 'no';
			        }
					if(typeof callback == 'function')
					{
						callback(returnRes,params);
					};
			    }
			});
		},
		urlencode:function(str) {
			str = (str + '').toString();
			return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
			replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
		},
		urldecode:function(zipStr){ 
		  var uzipStr = ''; 
		  for (var i = 0; i < zipStr.length; i += 1) {
		    var chr = zipStr.charAt(i); 
		    if (chr === '+') { 
		      uzipStr += ' ';
		    } else if (chr === '%') { 
		      var asc = zipStr.substring(i + 1, i + 3); 
		      if (parseInt('0x' + asc) > 0x7f) {
		        uzipStr += decodeURI('%' + asc.toString() + zipStr.substring(i+3, i+9).toString()); 
		        i += 8;
		      }else{ 
		        uzipStr += String.fromCharCode(parseInt('0x' + asc)); 
		        i += 2;
		      } 
		    }else{ 
		      uzipStr += chr; 
		    } 
		  } 
		
		  return uzipStr; 
		},
		checkIsHttpUrl:function(url){
			var str = url;
			//判断URL地址的正则表达式为:http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
			//下面的代码中应用了转义字符"\"输出一个字符"/"
			var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
			var objExp = new RegExp(Expression);
			if(objExp.test(str) == true){
				return true;
			}else{
				return false;
			}
		},
		navigateTo:function(url,url_type){
			var _this = this;
			url_type = url_type?url_type:1; //1站内跳转  2站外跳转
			if(!url)
			{
				_this.msg('缺少跳转链接');return ;
			}
			if(url_type == 1)
			{
				uni.navigateTo({
				    url: url,
					fail(res) {
						//尝试tabbar跳转
						uni.switchTab({
							url: url,
							fail(res) {
								_this.msg('无法跳转页面');
							}
						});
					}
				});
			}else if(url_type == 2){
				if(!_this.checkIsHttpUrl(url)){
					_this.msg('非完整的http链接');
					return false;
				}
				var token = apiObj.jwtToken();
				if(token && url.indexOf('token=') == -1)
				{
					//必须检测到token 而且这个url不带有token
					if(url.indexOf('?')> -1)
					{
						url = url+'&token='+token
					}else{
						url = url+'?token='+token 
					}
				}
				url = _this.urlencode(url);
				uni.navigateTo({
				    url: '/pages/common/show-webview?web_url='+url,
					fail(res) {
						_this.msg('无法跳转链接');
					}
				});
			}
		},
		navbackTo:function(delta){
			var pages = getCurrentPages();
			if(pages.length == 1)
			{
				uni.switchTab({
					url:'/pages/mine/index'
				})
				return ;
			}
			delta = delta?delta:1;
			uni.navigateBack({
				delta:delta
			});
		},
		openLocation:function(lat,lng,params)
		{
			var that = this;
			params = params?params:{};
			uni.openLocation({
				latitude: parseFloat(lat),
				longitude: parseFloat(lng), 
				scale:params.scale?params.scale:12,
				address:params.address?params.address:'',
				success: function () {
					//console.log('success');
				},
				fail(e){
					that.msg('显示地图位置失败：'+e.errno)
				}
			});
		},
		chooseLocation:function(callbackFunc){
			uni.authorize({
			    scope: 'scope.userLocation',
			    success(e) {
			        uni.getLocation({
			        	type: 'gcj02', //返回可以用于uni.openLocation的经纬度
			        	success: function (res) {
			        		const latitude = res.latitude;
			        		const longitude = res.longitude;
			        		uni.chooseLocation({
			        			latitude: latitude,
			        			longitude: longitude,
			        			success: function (e) {
									if(typeof callbackFunc == 'function')
									{
										callbackFunc(e)
									}
			        			},
			        		});
			        	},
			        }); 
			    },
				fail(e) {
					uni.showModal({
						title:'请先允许获取地理位置',
						confirmText:'去授权',
						success:function(res){
							if(res.confirm)
							{
								uni.openSetting({})
							}
						},
					})
					 
				}
			})
		},
		getLocation:function(callbackFunc){
			var that = this;
			uni.authorize({
			    scope: 'scope.userLocation',
			    success(e) {
			        uni.getLocation({
			        	type: 'wgs84', //返回可以用于uni.openLocation的经纬度
			        	success: function (res) {
							var lat = res.latitude;
							var lng = res.longitude;
							var postStr = `{"lon":${lng},"lat":${lat},"ver":1}`
							uni.request({
							    url: 'https://api.tianditu.gov.cn/geocoder?postStr='+postStr+'&type=geocode&tk=cbe3448ebe9025ff1a0a7fc6be6846a9', //仅为示例，并非真实接口地址。
							    success: (res) => {
									uni.hideLoading()
									//console.log(res)
									var data = res.data?res.data:{};
									if(data.result && data.result.formatted_address)
									{
										/* uni.showModal({
											content:JSON.stringify(data.result)
										}) */
										if(typeof callbackFunc == 'function')
										{
											callbackFunc({
												lat:lat,
												lng:lng,
												address:data.result.formatted_address
											})
										}
									}else{
										that.msg((res.msg?res.msg:'获取定位失败'));
									}
							    },
								fail(res){
									uni.hideLoading()
									that.msg((res.errMsg?res.errMsg:'获取定位位置异常'));
								}
							});
			        	},
						fail(res){
							uni.hideLoading()
							console.log("定位失败"+JSON.stringify(res))
							that.msg((res.errMsg?res.errMsg:'未获取到当前位置'));
						}
			        }); 
			    },
				fail(e) {
					uni.hideLoading();
					uni.showModal({
						title:'请先允许获取地理位置',
						confirmText:'去授权',
						success:function(res){
							if(res.confirm)
							{
								uni.openSetting({})
							}
						},
					})
					 
				}
			})
		},
		//处理表单数据
		opeDiyFormData(data){
			var data = data?data:[];
			var _this = this;
			if(data.length < 1)
			{
				_this.msg('未设置内容');
			}
			var unsetKey = ['icon','icon_size'];
			var hasErrorText = '';
			//console.log(data)
			for(var i=0;i<data.length;i++)
			{
				unsetKey.forEach(function(item){
					try{
						if(data[i].hasOwnProperty(item))
						{
							delete data[i][item];
						} 
					}catch(e){
						
					}
				})
				let info = data[i];
				var index = i+1;
				//info.value = info.value?info.value.trim():'';
				if(!info.value || info.value == '')
				{
					hasErrorText = '第'+index+'个设置的标题不能为空';
					break;
				}
				info.value.trim();
				if(info.type == 'radio' || info.type == 'checkbox')
				{
					var ext = info.ext?info.ext:[];
					if(ext.length < 1)
					{
						hasErrorText = '第'+index+'个设置最少有一个选项';
						break;
					}
					for(var y=0;y<ext.length;y++)
					{
						if(!ext[y] || ext[y] == '')
						{
							hasErrorText = '第'+index+'个设置,选项'+(y+1)+'不能为空';
							break; //跳出ext的循环
						}
						ext[y].trim();
					}
					info.ext = ext;
					if(hasErrorText)
					{
						break; //有错误跳出整个for循环
					}
				}
				data[i] = info;
			}
			if(hasErrorText)
			{
				_this.msg(hasErrorText);
				return [];
			}
			return data;
		},
		//获取md5名称
		getMd5Name(str,getRandomStr=true){
			if(getRandomStr == true)
			{
				str = str + this.getRandomStr(6);
			}
			return md5js.hex_md5(str)
		},
		//获取随机字符串
		getRandomStr(number){
		    var x='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789';
		    let str = ''
		    for(let i=0;i<number;i++){
		        //重点  这里利用了Math.random()函数生成的随机数大于0 小于1 我们可以
		        //用它的随机数来乘以字符串的长度,得到的也是一个随机值，再通过parseInt()
		        //函数取整，这样就可以实现字符串的随机取值了
		        str +=  x[parseInt(Math.random()*x.length)]
		    }
		    return str
		},
		copyText(text){
			var that = this;
			if(!text || text == '')
			{
				that.msg('未获取到复制内容');return;
			}
			switch(typeof text)
			{
				case 'number':
					text = text.toString();break;
				case 'object':
					text = JSON.stringify(text);break;
			}
			uni.setClipboardData({
				data: text,
				success: function () {
					that.msg('复制成功');
				},
				fail:function(){
					that.msg('复制失败');
				}
			});
		},
		openFile(url){
			var that = this;
			if(!url)
			{
				that.msg('缺少文件地址');return ;
			}
			that.loadingMsg('正在下载文件');
			//console.log(url)
			uni.downloadFile({
				url: url, 
				success: (res) => {
					uni.hideLoading();
					var filePath = res.tempFilePath?res.tempFilePath:'';
					uni.openDocument({
						filePath: filePath,
						showMenu: true,
						success: function (res) {
							console.log(res)
						},
						fail(e){
							that.msg('文件不存在或文件类型不支持');
						}
					});
				},
				fail(e){
					uni.hideLoading();
					that.msg('下载文件失败:'+(e.errMsg?e.errMsg:''));
				}
			});
		},
		joinRuleList(){
			return [
				{id:1,title:'所有人可见'},
				{id:2,title:'仅管理员可见'},
				{id:3,title:'参加者和管理员可见'}
			];
		},
		checkScopeRecord(callback){
			uni.authorize({
				scope: 'scope.record',
				success(e) {
					if(typeof callback == 'function')
					{
						callback(e)
					}
				},
			  fail() {
				uni.showModal({
					title:'请先允许使用麦克风',
					confirmText:'去授权',
					success:function(res){
						if(res.confirm)
						{
							uni.openSetting({})
						}
					},
				})
			  }
			})
		},
		checkPhotoRecord(callback){
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success(e) {
					if(typeof callback == 'function')
					{
						callback(e)
					}
				},
			  fail() {
				uni.showModal({
					title:'请先允许保存到相册',
					confirmText:'去授权',
					success:function(res){
						if(res.confirm)
						{
							uni.openSetting({})
						}
					},
				})
			  }
			})
		},
		showImage:function(urlArr){
			uni.previewImage({
				urls: urlArr,
				longPressActions: {
					itemList: [],
					success: function(data) {
						
					},
					fail: function(err) {
						console.log(err.errMsg);
					}
				}
			});
		},
		
		setCachePhoneMobile:function(type,mobile){
			type = type?type:'get';
			mobile = mobile?mobile:'';
			var key = 'api-obj-getPhoneMobile';
			var keytime = 'api-obj-getPhoneMobile-time';
			switch(type)
			{
				case 'set':
					uni.setStorageSync(key,mobile);
					uni.setStorageSync(keytime,this.getTime() + 3600 );
					break;
				case 'get':
					var mobile = uni.getStorageSync(key);
					if(!mobile || mobile == '')
					{
						return '';
					}
					var exp_time = uni.getStorageSync(keytime);
					if(exp_time < this.getTime())
					{
						this.setCachePhoneMobile('del');
						return '';
					}
					return mobile;
					break;
				case 'del':
					uni.removeStorageSync(key);
					uni.removeStorageSync(keytime);
					break
			}
		},
		getPhoneMobile:function(params,callback)
		{
			var that = this;
			var mobile = that.setCachePhoneMobile();
			if(mobile)
			{
				if(typeof callback == 'function')
				{
					callback({
						phone:mobile
					})
				}
				return;
			}
			that.loadingMsg('正在获取');
			http.post('config/getMobile',{
				code:params.code
			}).then(res=>{
				if(res.code == 1 && res.data.phone)
				{
					that.setCachePhoneMobile('set',res.data.phone)
					if(typeof callback == 'function')
					{
						callback({
							phone:res.data.phone
						})
					}
				}else{
					that.msg(res.msg)
				}
			})
			
		},
		getErrorImage(type){
			type = type?type:'image';
			var errorImage = this.getSystemConfig('errorImage');//myconfig.errorImage;
			return errorImage[type]?errorImage[type]:'';
		},
		async checkQiniuText(text='')
		{
			text = text.replace(/\n/g,',');
			text = text.replace(' ','');
			if(!text || text == '')
			{
				return true;
			}
			this.loadingMsg('正在检测内容');
			return new Promise((resolve, reject) =>  {
				//uniapi/qiniunotice/checkText
				http.post('wechat/checkText',{
					text
				}).then(res=>{
					if(res.code == 1){
						resolve({
							status:true
						});
					}else{
						var resData = res.data;
						this.showModal2(resData.title,resData.content,'',{
							hideCancel:true
						})
						//apiObj.msg(res.msg);
						resolve({
							status:false
						});
					}
				}).catch(res=>{
					this.msg('检测失败');
					resolve({
						status:false
					});
				})
			})
		},
		getSystemConfig:function(key)
		{
			var config = uni.getStorageSync('common-system-config');
			var keyArr = key?key.split('.'):[];
			switch(keyArr.length)
			{
				case 1:
					var res = config[keyArr[0]]?config[keyArr[0]]:{};
					break;
				case 2:
					var info = config[keyArr[0]]?config[keyArr[0]]:{};
					var res = info[keyArr[1]]?info[keyArr[1]]:{};
					break;
				default:
					var res = config;
					break;
			}
			return res;
		},
		updateVersion ()
		{
			let updateManager = uni.getUpdateManager();
			if (!updateManager) {
				return false;
			} else {
				//新版本更新
				if (uni.canIUse('getUpdateManager')) {
					//判断当前微信版本是否支持版本更新
					updateManager.onCheckForUpdate(function(res) {
						if (res.hasUpdate) {
							// 请求完新版本信息的回调
							updateManager.onUpdateReady(function() {
								uni.showModal({
									title: '更新提示',
									content: '新版本已经准备好，立即重启应用？',
									showCancel:false,
									success: function(res) {
										if (res.confirm) {
											// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
											updateManager.applyUpdate();
										}
									},
								});
							});
							updateManager.onUpdateFailed(function() {
								uni.showModal({
									// 新的版本下载失败
									title: '已经有新版本了哟~',
									content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
								});
							});
						} else {}
					});
				} else {
					uni.showModal({
						// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
						title: '提示',
						content: '当前微信版本过低，部分功能无法使用，请升级到最新微信版本后重试。',
					});
				}
		
			}
		}
	}
}
//点赞
export const vote = {
	methods: {
		likes: async function() {
			const value = uni.getStorageSync(`${this.id}_${this.vuex_user.id}`);
			if (value == this.id) {
				this.$u.toast('您已经点过赞了')
				return;
			}
			let res = await this.$api.getArchivesVote({
				id: this.id,
				type: 'like'
			})
			this.$u.toast(res.msg);
			if (!res.code) {
				return;
			};
			//先在前端限制
			uni.setStorageSync(`${this.id}_${this.vuex_user.id}`, this.id);
			this.$set(this.archivesInfo, 'likes', res.data.likes)
		},
		collection(id, type) {
			this.$api.addCollection({
				aid: id,
				type: type
			}).then(res => {
				this.$u.toast(res.msg)
			})
		}
	}
}
//修改头像的事件
export const avatar = {
	methods: {
		chooseAvatar() {
			uni.$on('uAvatarCropper', this.upload);
			this.$u.route({
				// 关于此路径，请见下方"注意事项"
				url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
				// 内部已设置以下默认参数值，可不传这些参数
				params: {
					// 输出图片宽度，高等于宽，单位px
					destWidth: 300,
					// 裁剪框宽度，高等于宽，单位px
					rectWidth: 300,
					// 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
					fileType: 'jpg'
				}
			});
		},
		upload: async function(path) {
			uni.$off('uAvatarCropper', this.upload);
			// 可以在此上传到服务端
			try {
				let res = await this.$api.goUpload({
					filePath: path
				});
				if (!res.code) {
					this.$u.toast(res.msg);
				};
				this.form.avatar = res.data.url;
				this.url = res.data.fullurl;
				if (typeof this.editAvatar == 'function') {
					this.editAvatar();
				}
			} catch (e) {
				console.error(e);
				this.$u.toast('图片上传失败！');
			}
		}
	}
}

//form
export const formRule = {
	methods: {
		//表单验证
		getRules(row) {
			let arr = row.rule.split(';');
			let rule_arr = [];

			arr.forEach(item => {
				item = this.$u.trim(item);
				switch (item) {
					case 'required':
					case 'checked':
						rule_arr.push({
							validator: (rule, value, callback) => {
								if (typeof value == 'string') {
									value = value.replace(/<[^>]+>/g, "").replace(/\s/ig, "");
								}
								return !(this.$u.test.empty(value));
							},
							message: row.title + '不能为空',
							// 可以单个或者同时写两个触发验证方式
							trigger: ['change', 'blur']
						});
						break;
					case 'digits': //数字校验
						rule_arr.push({
							validator: (rule, value, callback) => {
								return this.$u.test.digits(value);
							},
							message: '请填写数字',
							trigger: ['change', 'blur']
						});
						break;
					case 'letters': //字母校验
						rule_arr.push({
							validator: (rule, value, callback) => {
								return this.$u.test.letter(value);
							},
							message: '请填写字母',
							trigger: ['change', 'blur']
						});
						break;
					case 'date': //日期校验
						rule_arr.push({
							validator: (rule, value, callback) => {
								return this.$u.test.date(value);
							},
							message: '请填写正确日期格式',
							trigger: ['change', 'blur']
						});
						break;
					case 'time': //时间校验
						rule_arr.push({
							validator: (rule, value, callback) => {
								return /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(value);
							},
							message: '请填写正确时间格式',
							trigger: ['change', 'blur']
						});
						break;
					case 'email': //邮箱校验
						rule_arr.push({
							validator: (rule, value, callback) => {
								return this.$u.test.email(value);
							},
							message: '请填写正确邮箱',
							trigger: ['change', 'blur']
						});
						break;
					case 'url': //网址
						rule_arr.push({
							validator: (rule, value, callback) => {
								return this.$u.test.url(value);
							},
							message: '请填写正确网址',
							trigger: ['change', 'blur']
						});
						break;
					case 'qq': //qq
						rule_arr.push({
							validator: (rule, value, callback) => {
								return /^[1-9][0-9]{4,10}$/.test(value);
							},
							message: '请填写正确QQ号码',
							trigger: ['change', 'blur']
						});
						break;
					case 'IDcard': //身份证
						rule_arr.push({
							validator: (rule, value, callback) => {
								return this.$u.test.idCard(value);
							},
							message: '请填写正确身份证件号',
							trigger: ['change', 'blur']
						});
						break;
					case 'tel': //电话
						rule_arr.push({
							validator: (rule, value, callback) => {
								return /^\d{3}-\d{8}$|^\d{4}-\d{7,8}$/.test(value);
							},
							message: '请填写正确电话号码',
							trigger: ['change', 'blur']
						});
						break;
					case 'mobile': //手机
						rule_arr.push({
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '请填写正确手机号码',
							trigger: ['change', 'blur']
						});
						break;
					case 'zipcode': //邮编
						rule_arr.push({
							validator: (rule, value, callback) => {
								return /^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\d{4}$/
									.test(value);
							},
							message: '请填写正确邮编',
							trigger: ['change', 'blur']
						});
						break;
					case 'chinese': //中文
						rule_arr.push({
							validator: (rule, value, callback) => {
								return /^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/
									.test(
										value
									);
							},
							message: '请填写中文',
							trigger: ['change', 'blur']
						});
						break;
					case 'username': //用户名
						rule_arr.push({
							validator: (rule, value, callback) => {
								return /^[a-zA-Z0-9_]{3,12}$/.test(value);
							},
							message: '请填写3-12位数字、字母、下划线',
							trigger: ['change', 'blur']
						});

						break;
					case 'password': //密码
						rule_arr.push({
							validator: (rule, value, callback) => {
								let val = this.$u.trim(value, 'all');
								if (val != value) {
									return false;
								}
								return /^[0-9a-zA-Z!@#$%^&*?]{6,16}$/.test(value);
							},
							message: '请填写6-16位字符，不能包含空格',
							trigger: ['change', 'blur']
						});
						break;
				}
			});


			//多选额外的判断
			if (row.type == 'checkbox') {
				//最少
				if (row.minimum > 0) {
					rule_arr.push({
						validator: (rule, value, callback) => {
							if (!value) {
								return false;
							}
							let arr = value.split(',')
							return arr.length >= row.minimum;
						},
						message: '最少必须选择' + row.minimum + '项',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					});
				}
			}
			if (['checkbox', 'selects', 'images', 'files'].indexOf(row.type) != -1) {
				//最多
				if (row.maximum > 0) {
					rule_arr.push({
						validator: (rule, value, callback) => {
							if (!value) {
								return false;
							}
							let arr = value.split(',')
							return arr.length <= row.maximum;
						},
						message: '最多只能选择' + row.maximum + '项',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					});
				}
			}

			return rule_arr;
		}
	}
}

//登录成功跳转
export const loginfunc = {
	methods: {
		//登录成功
		success(index = 1) {
			//不在H5
			// #ifndef H5
			uni.$u.route({
				type: 'back',
				delta: index
			})
			// #endif
			// 在H5 刷新导致路由丢失
			// #ifdef H5
			var pages = getCurrentPages();
			//有上次页面，关闭所有页面，到此页面,是从授权的，授权页面被刷新过,路由栈丢失
			if (pages.length <= 1 || pages[0].route == 'pages/login/auth') {
				//默认到首页
				uni.reLaunch({
					url: (this.vuex_lasturl || '/pages/mine/index'),
					complete(res) {
						console.log(res)
					}
				})
				return;
			}
			uni.$u.route({
				type: 'back',
				delta: index
			})
			// #endif
		},
		// #ifdef H5
		async goAuth() {
			if (this.$util.isWeiXinBrowser()) {
				let url = '';
				if (window.location.hash != '') {
					url = window.location.origin + window.location.pathname + '?hashpath=/pages/login/auth'
				} else {
					url = window.location.origin + window.location.pathname.replace(/pages.*/,
						'pages/login/auth');
				};
				let res = await this.$api.getAuthUrl({
					platform: 'wechat',
					url: url
				});
				if (!res.code) {
					this.$u.toast(res.msg);
					return;
				}
				var pages = getCurrentPages();
				let len = pages.length;
				if (len > 1) {
					let url = pages[len - 1].route;
					if (url.includes('login')) {
						//找到上一个不是登录页面
						for (let i = len - 1; i >= 0; i--) {
							if (!pages[i].route.includes('login')) {
								this.$u.vuex('vuex_lasturl', '/' + pages[i].route + this.$u.queryParams(pages[i]
									.options));
								break;
							}
						}
					} else {
						this.$u.vuex('vuex_lasturl', '/' + url + this.$u.queryParams(pages[pages.length - 1]
							.options))
					}
				}
				window.location.href = res.data;
			}
		},
		// #endif
		// #ifdef APP-PLUS
		goAppLogin(index = 1) {
			let that = this;
			var all, Service;
			// 1.发送请求获取code
			plus.oauth.getServices(
				function(Services) {
					all = Services;
					Object.keys(all).some(key => {
						if (all[key].id == 'weixin') {
							Service = all[key];
						}
					});
					Service.authorize(
						async function(e) {
								console.log(e);
								let res = await that.$api.goAppLogin({
									code: e.code,
									scope: e.scope
								});
								if (!res.code) {
									that.$u.toast(res.msg);
									return;
								}
								if (res.data.user) {
									that.$u.vuex('vuex_token', res.data.user.token);
									that.$u.vuex('vuex_user', res.data.user || {});
									that.success(index);
									return;
								}
								that.$u.vuex('vuex_third', res.data.third);
								that.$u.route('/pages/login/register?bind=bind');
							},
							function(e) {
								that.$u.toast('授权失败！');
							}
					);
				},
				function(err) {
					console.log(err);
					that.$u.toast('授权失败！');
				}
			);
		}
		// #endif
	}
}
